package com.two.screen.water.balance.ui.fragment.base

import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import butterknife.ButterKnife
import butterknife.Unbinder

import com.two.screen.water.balance.ui.activity.base.BaseActivity
import com.two.screen.water.balance.utils.CommUtils
import com.two.screen.water.balance.widget.statueslayoutmanager.DefaultOnStatusChildClickListener
import com.two.screen.water.balance.widget.statueslayoutmanager.StatusLayoutManager
import com.trello.rxlifecycle2.components.support.RxFragment
import com.two.screen.water.balance.utils.eventbus.Event
import com.two.screen.water.balance.utils.eventbus.EventBusUtil
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode


/**
 * 创建者     Noel
 * 创建时间   2017/12/25 9:44
 */
abstract class BaseFragment : RxFragment() {
    lateinit var mFragmentNavigation: FragmentNavigation

    /*Log信息的标记*/
    protected var mClassTag = javaClass.simpleName

    /*贴附的activity*/
    lateinit var mActivity: BaseActivity

    /*根view*/
    var mRootView: View? = null

    /*是否对用户可见*/
    private var mIsVisible: Boolean = false

    /*是否加载完成，当执行完onCreateView,View的初始化方法后即为true*/
    private var mIsPrepare: Boolean = false

    private var mEventCode: Int = 0

    val mStatusLayoutManager: StatusLayoutManager by lazy {
        StatusLayoutManager.Builder(getRootLayout())
            .setDefaultErrorClickViewVisible(setDefaultErrorClickViewVisible)
            .setDefaultEmptyClickViewVisible(setDefaultEmptyClickViewVisible)
            .setOnStatusChildClickListener(object : DefaultOnStatusChildClickListener() {
                override fun onEmptyChildClick(view: View?) {
                    onEmptyChildClick()
                }

                override fun onErrorChildClick(view: View?) {
                    onErrorChildClick()
                }
            })
            .build()
    }

    /*基于那个视图上 放一个 加载页或者错误、空白页面。*/
    open fun getRootLayout(): View = View(context)

    protected var setDefaultErrorClickViewVisible = true
    protected var setDefaultEmptyClickViewVisible = false
    open fun onEmptyChildClick() {}
    open fun onErrorChildClick() {}

    override fun onAttach(context: Context) {
        super.onAttach(context)
        mActivity = activity as BaseActivity
        if (context is FragmentNavigation) {
            mFragmentNavigation = context
        }
    }

    var unbinder: Unbinder? = null
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        if (mRootView == null) {
            mRootView = inflater.inflate(setLayoutResouceId(), container, false)
            unbinder = ButterKnife.bind(this, mRootView!!)
            initView()
            initData(arguments)
            initListener()
            d("===>mIsVisible:$mIsVisible,mIsPrepare:$mIsPrepare")
            if (mIsVisible && !mIsPrepare) {
                //可见状态，一般是第一次调用。
                mIsPrepare = true
                onLazyLoad()
            }
            if (mIsFirstFragment && setOnLazyLoad()) {
                onLazyLoadByHiddenChanged()
            }
        }
        if (isRegisterEventBus()) EventBusUtil.register(this)
        val parent = mRootView!!.parent
        if (parent != null) (parent as ViewGroup).removeView(mRootView)
        return mRootView
    }

    protected var mIsFirstFragment = isFirstFragment() //Fragment是否第一个。因为第一个没加载onHiddenChanged

    protected open fun isFirstFragment() = false

    protected var mIsFirstVisiable = true //Fragment是否第一次可见

    protected var mCurrentVisiableState = false //标记保存Fragment的可见状态，表示当前Fragment是否分发过，


    /**
     * 分发可见
     * 调用的前提：可见--》不可见    或者不可见--》可见
     * @param isVisiable
     */
    open fun disPatchVisibaleHint(isVisiable: Boolean) {
        d("disPatchVisibaleHint----$isVisiable")
        if (mCurrentVisiableState == isVisiable) {
            //防止调用两次更新，存在当 mCurrentVisiableState=isVisiable;执行前setUserVisibleHint可能被调用两次
            return
        }
        mCurrentVisiableState = isVisiable //进行赋值操作
        if (isVisiable) {
            //可见
            if (mIsFirstVisiable) {
                mIsFirstVisiable = false
                //处理第一次可见时
                //公共方法，由子类实现
                if (setOnLazyLoad() && !mIsFirstFragment) {
                    onLazyLoadByHiddenChanged()
                }
            }
            //复写onFragmentResume分发事件，网路请求
            //onFragmentResume()
            //对viewpager嵌套使用时处理子的fragment
        } else {
            //复写onFragmentPause终止数据请求
            //onFragmentPause()
        }
    }

    override fun onHiddenChanged(hidden: Boolean) {
        d("懒加载：onHiddenChanged：hidden:$hidden")
        if (hidden) {
            disPatchVisibaleHint(false)
        } else {
            disPatchVisibaleHint(true)
        }
    }

    override fun setUserVisibleHint(isVisibleToUser: Boolean) {
        super.setUserVisibleHint(isVisibleToUser)
        d("懒加载：setUserVisibleHint：isVisibleToUser:$isVisibleToUser,!mIsPrepare:${!mIsPrepare}")
        if (setOnLazyLoad()) {
            mIsVisible = isVisibleToUser
            if (mRootView != null && mIsVisible && !mIsPrepare) {
                mIsPrepare = true
                onLazyLoad()
            }
        }
    }

    /*设置布局的id*/
    protected abstract fun setLayoutResouceId(): Int

    protected abstract fun initView()

    protected abstract fun initData(arguments: Bundle?)

    protected abstract fun initListener()

    /*true表示启用懒加载*/
    protected open fun setOnLazyLoad(): Boolean = false

    /*懒加载的内容*/
    protected open fun onLazyLoad() {}

    /*懒加载的内容*/
    protected open fun onLazyLoadByHiddenChanged() {}


    interface FragmentNavigation {
        fun pushFragment(fragment: Fragment, sharedElementList: List<Pair<View, String>>? = null)
        fun popFragment()
    }

    protected fun d(msg: String) {
        CommUtils.println("$mClassTag->", msg)
    }

    /**
     * 是否注册事件分发
     *
     * @return true绑定EventBus事件分发，默认不绑定，子类需要绑定的话复写此方法返回true.
     */
    protected open fun isRegisterEventBus(): Boolean = false

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEventBusCome(event: Event<Any>?) {
        if (event != null) {
            mEventCode = event.code
            receiveEvent(event)
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    fun onStickyEventBusCome(event: Event<Any>?) {
        if (event != null) {
            mEventCode = event.code
            receiveStickyEvent(event)
        }
    }

    /**
     * 接收到分发到事件
     *
     * @param event 事件
     */
    protected open fun receiveEvent(event: Event<Any>) {
        // mEventCode = event.getCode();
    }

    /**
     * 接受到分发的粘性事件
     *
     * @param event 粘性事件
     */
    protected open fun receiveStickyEvent(event: Event<Any>) {
        //mEventCode = event.getCode();
    }

    override fun onDestroy() {
        if (isRegisterEventBus()) EventBusUtil.unregister(this)
        unbinder?.unbind()
        super.onDestroy()
    }
}